package net.libra.ui.base
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import net.libra.ui.event.BaseEvent;
	import net.libra.utils.DisplayUtil;
	
	[Event(name="baseDestroy",type="net.libra.ui.event.BaseEvent")]
	
	
	/**
	 * 组件基类 
	 * @author elvisjiang
	 * 
	 */	
	public class BaseSprite extends Sprite
	{
		/**
		 * 标志此对象是否忆被销毁 
		 */		
		private var _destroyed:Boolean;
		
		/**
		 * 数据 
		 */		
		private var _data:Object;
		
		public function BaseSprite()
		{
			super();
			_listener = [];
			_destroyed = false;
			mouseChildren = false;
			mouseEnabled = false;
//			cacheAsBitmap = true;
		}
		
		
		public function get data():Object
		{
			return _data;
		}

		public function set data(value:Object):void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
			_data = value;
			dispatchEvent(new BaseEvent(BaseEvent.DATA_CHANGE));
			update();
		}
		public function update():void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
			_isNeedUpdate = true;
			addEventListener(Event.ENTER_FRAME,_render);
		}
		private var _isNeedUpdate:Boolean;
		public function get isNeedUpdate():Boolean
		{
			return _isNeedUpdate;
		}
		public function updateNow():void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
			_isNeedUpdate = false;
			removeEventListener(Event.ENTER_FRAME,_render);
			render();
		}
		private function _render(event:Event):void
		{
			updateNow();
		}
		protected function render():void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
		}

		public function get destroyed():Boolean
		{
			return _destroyed;
		}
		
		private var _listener:Array;
		public override function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
			if(!_listener)
			{
				_listener = [];
			}
			
			_listener.push({type:type,listener:listener,useCapture:useCapture});
			super.addEventListener(type,listener,useCapture,priority,useWeakReference);
//			trace(type,listener);
		}
		
		public function destroy():void
		{
			//已经移除，返回
			if(destroyed)
			{
				return;
			}
			
			//设置移除标志
			_destroyed = true;
			
			//清空数据
			_data = null;
			
			_isNeedUpdate = false;
			
			//清空绘制ｓ
			graphics.clear();
			
			//移除自身
			if(parent)
			{
				parent.removeChild(this);
			}
			//移除子级
			DisplayUtil.removeAllChildren(this);
			dispatchEvent(new BaseEvent(BaseEvent.BASE_DESTROY));
			
			//移除监听
			while(_listener.length > 0)
			{
				var item:Object = _listener.shift();
				removeEventListener(item.type,item.listener,item.useCapture);
			}
			_listener = [];
			
		}
	}
}